package com.yeqifu.bus.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.yeqifu.bus.domain.Car;
import com.yeqifu.bus.domain.Rent;
import com.yeqifu.bus.service.ICarService;
import com.yeqifu.bus.service.IRentService;

import com.yeqifu.bus.vo.RentVo;
import com.yeqifu.sys.constast.SysConstast;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static com.alipay.api.AlipayConstants.*;
import static com.yeqifu.bus.constant.SysConstant.*;
import static com.yeqifu.bus.constant.SysConstant.APP_ID;
import static com.yeqifu.bus.constant.SysConstant.CHARSET;
import static com.yeqifu.bus.constant.SysConstant.FORMAT;

@Controller
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private IRentService rentService;
    @Autowired
    private ICarService carService;
    @Autowired
    private HttpSession session;
    //必须加ResponseBody注解，否则spring会寻找thymeleaf页面
    @RequestMapping("/alipay")
    @ResponseBody
    public String alipay(RentVo rentVo) throws AlipayApiException {
        //把dona_id项目id 放在session中
        //生成订单号（支付宝的要求？）
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String user = UUID.randomUUID().toString().replace("-","").toUpperCase();

        String OrderNum = time+user;
        session.setAttribute(OrderNum,rentVo);
        System.out.println(OrderNum);
        //调用封装好的方法（给支付宝接口发送请求）
        return sendRequestToAlipay(rentVo.getRentid(),new Float(rentVo.getPrice()),rentVo.getRentid());
    }
    /*
参数1：订单号
参数2：订单金额
参数3：订单名称
 */
    //支付宝官方提供的接口
    private String sendRequestToAlipay(String outTradeNo,Float totalAmount,String subject) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL,APP_ID,APP_PRIVATE_KEY,FORMAT,CHARSET,ALIPAY_PUBLIC_KEY,SIGN_TYPE_RSA2);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setNotifyUrl("http://i6pj5d.natappfree.cc/carRental_war/pay/notify.action");
        alipayRequest.setReturnUrl("http://i6pj5d.natappfree.cc/carRental_war/business/toRentManager.action");
        //商品描述（可空）
        String body="";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\","
                + "\"total_amount\":\"" + totalAmount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest,"GET").getBody();
        return result;
    }

    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            Map<String,String> params = new HashMap<>();
            Map<String,String> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }
            String tradeNo = params.get("out_trade_no");
            Rent rent = rentService.queryRentByRentId(tradeNo);
            RentVo  rentVo = new RentVo();
            BeanUtils.copyProperties(rent,rentVo);
            //变更状态
            try {
                //修改出租单的状态
                rentVo.setRentflag(SysConstast.RENT_BACK_FALSE);
                rentService.updateRent(rentVo);
                //修改汽车的状态
                Car car = carService.queryCarByCarNumber(rentVo.getCarnumber());
                car.setIsrenting(SysConstast.RENT_CAR_TRUE);
                this.carService.updateCarCheck(car);
            }catch (Exception e){
                e.printStackTrace();
            }

        }
        return "sussec";
    }

}
